package com.lxd.kyvideo.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxd.kyvideo.common.ApiResult;
import com.lxd.kyvideo.dto.AdminDTO;
import com.lxd.kyvideo.mapper.AdminMapper;
import com.lxd.kyvideo.pojo.User;
import com.lxd.kyvideo.service.AdminService;
import com.lxd.kyvideo.vo.AdminVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, User> implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Transactional
    @Override
    public ApiResult adminLogin(AdminVO userVO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone_number",userVO.getLoginId());
        User userEntity = adminMapper.selectOne(queryWrapper);
        if (userEntity == null) {
            return ApiResult.fail("此账号不存在！");
        }
        else if(! userEntity.getPassword().equals(userVO.getLoginPwd())){
            return ApiResult.fail("登录密码错误！");
        }
        else if(userEntity.getUserStatus() == 1){
            return ApiResult.fail("登录失败，此账号已被禁用！");
        }
        else if(userEntity.getUserType() != 0){
            return ApiResult.fail("登录失败，您不是后台管理员！");
        }
        else {
            String token = UUID.fastUUID().toString(true);
            AdminDTO adminDTO = new AdminDTO();
            adminDTO.setUserId(userEntity.getId());
            adminDTO.setPhoneNumber(userEntity.getPhoneNumber());
            adminDTO.setNickName(userEntity.getNickName());
            adminDTO.setToken(token);
            adminDTO.setVisitCount(userEntity.getVisitCount());
            adminDTO.setAvatarUrl(userEntity.getAvatarUrl());
            Object adminObj = redisTemplate.opsForValue().get(token);
            if(adminObj == null) {
                redisTemplate.opsForValue().set(token,adminDTO,300,TimeUnit.SECONDS);
            }
            return ApiResult.ok(adminDTO,"恭喜您，登录成功！");
        }
    }
}
